package com.yzd.learnjava.annotaions;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.declaration.MethodDeclaration;
import com.sun.mirror.declaration.Modifier;
import com.sun.mirror.declaration.ParameterDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;

public class InterfaceExtractorProcessor implements AnnotationProcessor{

	private final AnnotationProcessorEnvironment env;
	private ArrayList<MethodDeclaration> mes = new ArrayList<MethodDeclaration>();
	
	public InterfaceExtractorProcessor(AnnotationProcessorEnvironment env) {
		this.env = env;
	}
	
	public void process() {
		for(TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) {
			ExtractInterface annot = typeDecl.getAnnotation(ExtractInterface.class);
			if(annot == null) {
				break;
			}
			
			for(MethodDeclaration md : typeDecl.getMethods()) {
				if(md.getModifiers().contains(Modifier.PUBLIC) &&
						!md.getModifiers().contains(Modifier.STATIC)) {
					mes.add(md);
				}
			}
			
			if(mes.size() > 0) {
				try {
					PrintWriter writer = env.getFiler().createSourceFile(annot.value());
					writer.println("package " + typeDecl.getPackage().getQualifiedName());
					writer.println("public interface " + annot.value() + "{");
					for(MethodDeclaration me : mes) {
						writer.print("	public ");
						writer.print(me.getReturnType() + " ");
						writer.print(me.getSimpleName() + " (");
						int i = 0;
						for(ParameterDeclaration pd : me.getParameters()) {
							writer.print(pd.getType() + " " + pd.getSimpleName());
							if(++i < me.getParameters().size()) {
								writer.print(", ");
							}
						}
						
						writer.println(");");
					}
					writer.println("}");
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}
}
